const Client = require('../model/article.model')
const BookShare = require('../model/book_share.model')
const BookPV = require('../model/book_pv.model');
const ArticleType = require('../model/article_type.model')
const ArticleColumn = require('../model/article_column.model')
const Article = require('../model/article.model')
const moment = require('moment');
const { Op, Sequelize } = require("sequelize");
const ArticleCount = require('../model/article_count.model');
const ArticleLiked = require('../model/article_liked.model');
const seq = require('../db/seq');
const KeyWord = require('../model/keyword.model');
class ClientService {
    // 因为存入数据库 是异步的
    async saveArticle(
        html,
        user_id,
        title,
        username,
        date,
        type,
        column,
        cover,
        publish,
        desc) {
        const res = await Article.create({
            html,
            user_id,
            title,
            username,
            date,
            type,
            column,
            cover,
            publish,
            desc,
            check: 0
        })
        //    返回到controller
        return res
    }
    async ArticleTypeService() {
        const res = await ArticleType.findAll({
            attributes: ['id', 'type'],
        })
        console.log(res)
        // dataValues 是查到的值
        return res
        // ?res.dataValues : ''
    }
    // 查询专栏
    async ArticleColumnService(user_id) {
        const res = await ArticleColumn.findAll({
            where: {
                user_id: user_id,
                examine: 1
            }
        })
        return res
    }
    // 创建专栏
    async createArticleColumnService({ username, user_id, column, column_detail }) {
        const res = await ArticleColumn.create({ username, user_id, column, column_detail })
        console.log(res, 'create')
    }
    async getArticleService(params) {
        const { id, username, user_id, type, title, column, currentPage, pageSize, publish, check } = params
        const where = {};
        id && (where['id'] = {
            [Op.eq]: id
        })
        username && title && where[Op.and]
        user_id && (where['user_id'] = {
            [Op.eq]: user_id
        })
        type && (where['type'] = {
            [Op.eq]: type
        })
        column && (where['column'] = {
            [Op.eq]: column
        })
        publish && (where['publish'] = {
            [Op.eq]: publish
        })
        check && (where['check'] = {
            [Op.eq]: check
        })
        if (username || title) {
            where[Op.and] = [{
                [Op.or]: [
                    username && { username: { [Op.like]: `%${username}%` } },
                    title && { title: { [Op.like]: `%${title}%` } }
                ]
            }]
        }

        const { count, rows } = await Article.findAndCountAll({
            where,
            order: [
                ['createdAt', 'DESC'],
            ],
            offset: (currentPage - 1) * pageSize,
            limit: Number(pageSize),
        })
        username && title && await KeyWord.create({ keyword: username })
        return rows ? { data: rows, total: count } : { error: 500 }
    }
    // 更新文章
    async updateArticleService(params) {
        const { id, type, title, column, publish, html, reason, cover,
            check, verifier } = params

        let obj = {}
        type && (obj['type'] = type)
        title && (obj['title'] = title)
        column && (obj['column'] = column)
        html && (obj['html'] = html)
        reason && (obj['reason'] = reason)
        check && (obj['check'] = check)
        cover && (obj['cover'] = cover)
        publish && (obj['publish'] = publish)
        obj['checkdate'] = moment(new Date()).format('YYYY-MM-DD hh:mm:ss')
        verifier && (obj['verifier'] = verifier)
        console.log(obj)
        const res = await Article.update(obj, {
            where: {
                id: id,
            }
        })
        console.log(res, '🚀')
        return res[0] > 0 ? { status: 'success', code: 1000 } : { status: 'error', code: 1001 }
    }
    // 我点赞的
    async givePraiseArticleService(params) {
        const { title, column, operateuser_id, currentPage, pageSize } = params
        let result;
        try {
            //   seq是定义的数据库实例
            await seq.query(`SELECT * FROM Articles WHERE id IN (SELECT article_id FROM ArticleLikeds WHERE operateuser_id = ${operateuser_id})`, { type: seq.QueryTypes.SELECT }).then((res) => {
                //  return 不能写到promise中
                result = res
            })
            return result
        } catch (err) {
            console.log(err)
            return err
        }
    }
    // 点赞我的
    async getPraiseArticleService(params) {
        const { title, column, authoruser_id, currentPage, pageSize } = params
        let result;
        try {
            //   seq是定义的数据库实例
            await seq.query(` SELECT * FROM Articles WHERE id IN (SELECT article_id FROM ArticleLikeds WHERE authoruser_id = ${authoruser_id})`, { type: seq.QueryTypes.SELECT }).then((res) => {
                //  return 不能写到promise中
                result = res
            })
            return result
        } catch (err) {
            console.log(err)
            return err
        }
    }
    // 
    async saveBookService(params) {
        const { title, author, img_url, file_url, type } = params

        try {
            const res = await BookShare.create({
                title, author, img_url, file_url, type
            })
            //    返回到controller
            return res
        } catch (err) {
            console.log(err)
            return err
        }
    }
    async getBookListService(param) {
        const { title, author, type, pageSize, currentPage } = param
        const where = {};
        type && (where['type'] = {
            [Op.like]: type
        })
        if (author || title) {
            where[Op.and] = [{
                [Op.or]: [
                    author && { author: { [Op.like]: `%${author}%` } },
                    title && { title: { [Op.like]: `%${title}%` } }
                ]
            }]
        }
        const { count, rows } = await BookShare.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize,
            limit: Number(pageSize),
        });
        console.log(rows)
        return rows ? { data: rows, total: count } : { error: 500 }

    }

    async saveBookVisitNumService(param) {
        const { title, author, file_url, id } = param;
        const where = {
            id: { [Op.eq]: id }
        }

        const res = await BookPV.findOne({
            where
        })
        // 没有查到
        if (!res) {
            const data = await BookPV.create({ title, author, file_url, id, pv: 0 })
            return 'success'
        } else {
            // 查到之后更改
            const data = await BookPV.update({ pv: Number(res.pv) + 1 }, {
                where: { id }
            })
            return 'success'
        }
        return 'error'
    }
    async getBookTopService() {
        let result;
        try {
            //   seq是定义的数据库实例  必须加await
            await seq.query(`(SELECT pv,title,author FROM BookPvs GROUP BY id ORDER BY pv DESC)`, { type: seq.QueryTypes.SELECT }).then((res) => {
                result = res
                console.log(res)
            })
            return result

        } catch (err) {
            console.log(err)
            return err
        }

    }

    // // 访问量
    // async pageViewService(param) {
    //     const { id } = param;
    //     const where = {
    //         id: { [Op.eq]: id }
    //     }
    //     const res = await ArticleCount.findOne({
    //         where
    //     })
    //     console.log(res, '🚀')
    //     if (!res) {
    //         const data = await ArticleCount.create({ id })
    //         console.log(data)
    //         return 'success'
    //     } else {
    //         const data = await ArticleCount.update({ PV: Number(res.dataValues.PV) + 1 }, {
    //             where: { id }
    //         })
    //         console.log(data)
    //         return 'success'
    //     }

    // }
    // // 点赞
    // async givePraiseService(param) {
    //     const { id, author, authoruser_id, operateuser, title, operateuser_id } = param
    //     const where = {
    //         id: { [Op.eq]: id },
    //         operateuser_id: { [Op.eq]: operateuser_id }
    //     }
    //     console.log(where, '-------------')
    //     const res = await ArticleLiked.findOne({
    //         where
    //     })
    //     console.log(res, "!!!!!!!")
    //     console.log(typeof res)
    //     if (!res) {
    //         console.log('🌶', id, author, authoruser_id, operateuser, title, operateuser_id)
    //         const data = await ArticleLiked.create({ id: id, author: author, authoruser_id: authoruser_id, operateuser: operateuser, title: title, operateuser_id: operateuser_id })
    //         console.log(data)
    //         return 'success'
    //     } else {
    //         console.log(2222222222)
    //         return 'have'

    //     }
    //     console.log(11)
    // }
    // async getArticleService(params) {
    //     const { id, username, user_id, type, title, column, createdAtFrom, createdAtTo, updatedAtFrom, updatedAtTo, publish, check, checkdateFrom, checkdateTo, verifier, currentPage, pageSize } = params
    //     const where = {};
    //     id && (where['id'] = {
    //         [Op.eq]: id
    //     })
    //     username && (where['username'] = {
    //         [Op.like]: username
    //     })
    //     user_id && (where['user_id'] = {
    //         [Op.eq]: user_id
    //     })
    //     type && (where['type'] = {
    //         [Op.eq]: type
    //     })
    //     column && (where['column'] = {
    //         [Op.eq]: column
    //     })
    //     title && (where['title'] = {
    //         [Op.like]: title
    //     })
    //     createdAtFrom && (where['createdAt'] = {
    //         [Op.between]: [createdAtFrom, createdAtTo]
    //     })
    //     updatedAtFrom && (where['updatedAt'] = {
    //         [Op.between]: [updatedAtFrom, updatedAtTo]
    //     })
    //     publish && (where['publish'] = {
    //         [Op.eq]: publish
    //     })
    //     check && (where['check'] = {
    //         [Op.eq]: check
    //     })
    //     checkdateFrom && (where['checkdate'] = {
    //         [Op.between]: [checkdateFrom, checkdateTo]
    //     })
    //     verifier && (where['verifier'] = {
    //         [Op.like]: verifier
    //     })
    //     const { count, rows } = await Article.findAndCountAll({
    //         where,
    //         offset: (currentPage - 1) * pageSize,
    //         limit: Number(pageSize),
    //     })
    //     return rows ? { data: rows, total: count } : { error: 500 }
    // }
}
// 导出后 在控制器controller中使用
module.exports = new ClientService()